﻿@{
    ViewData["Title"] = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


<link href="~/assets/css/bootstrap-datetimepicker.css" rel="stylesheet" />
<style>
    img {
        width: 16px;
        height: 16px;
        background-size: 100%;
        background: no-repeat;
    }

    .odd {
        cursor: pointer;
    }

    .red {
        color: red;
    }

    .blue {
        color: dodgerblue;
    }

    .green {
        color: green;
    }

    .cursor {
        cursor: pointer
    }

    .selected {
        background-color: #fa7f51;
        -webkit-box-shadow: 1px 1px 1px;
    }

    .text-grays {
        color: #909080;
    }
</style>

<div class="breadcrumbs ace-save-state" id="breadcrumbs">
    <ul class="breadcrumb">
        <li>
            <i class="ace-icon fa fa-home home-icon"></i>
            <a href="~/Home/Index">首页</a>
        </li>
        <li>
            <a href="#">投注管理</a>
        </li>
        <li class="active">方案</li>
    </ul>

</div>
<p></p>

<div class="row">

    <div class="col-xs-12">

        <h3 class="row header smaller lighter blue">
            <div class="col-sm-3" style="width:365px!important;">
                <span class="box-title">账号</span>



            </div><!-- /.col -->
            <div style="width:calc(100%-365px)!important;">
                <label>
                    <span id="oddUserName" style="color:red; cursor:pointer"></span>&nbsp;&nbsp; <span id="remark"></span>&nbsp;&nbsp;
                    <a href="#" id="ab">￥<span>0</span></a>
                </label>

                <label class="pull-right inline">


                    <label>
                        <input name="oddMoneyType" class="ace" type="checkbox" value="1" checked="checked">
                        <span class="lbl"> 百</span>
                    </label>
                    <label>
                        <input name="oddMoneyType" class="ace" type="checkbox" value="2"  checked="checked">
                        <span class="lbl"> 千</span>
                    </label>
                    <label> 
                        <input name="oddMoneyType" class="ace" type="checkbox" value="3"  checked="checked">
                        <span class="lbl"> 万</span>
                    </label>
                    <label style="margin-right:10px;">
                        <select id="oddState">
                            <!--预约=1,撤销=2,已上传=3,比赛中=4,待确认=5,完成=6-->
                            <option selected="selected" value="0">全部状态</option>
                            <option value="0">预约</option>
                            <option value="1">撤销</option>
                            <option value="2">待上传</option>
                            <option value="3">已上传</option>
                            <option value="4">比赛中</option>
                            <option value="5">待确认</option>
                            <option value="6">完成</option>
                        </select>
                    </label>

                    <button class="btn btn-sm btn-primary" id="btnDownload" type="button" data-original-title="导出excel" data-toggle="tooltip" data-widget="">
                        <i class="fa fa-plus-square"></i>&nbsp;&nbsp;导出
                    </button>
                    @*<button class="btn btn-sm btn-primary" id="btnAdd" type="button" data-original-title="新增投注" data-toggle="tooltip" data-widget="">
                        <i class="fa fa-plus-square"></i>&nbsp;&nbsp;新增
                    </button>*@
                    <button class="btn btn-sm btn-primary hide" id="btnEditContent" type="button" data-original-title="编辑投注" data-toggle="tooltip" data-widget="">
                        <i class="fa fa-plus-square"></i>&nbsp;&nbsp;投注
                    </button>
                    <button class="btn btn-sm btn-primary hide" id="btnEdit" type="button" data-original-title="编辑" data-toggle="tooltip" data-widget="">
                        <i class="fa fa-edit"></i>&nbsp;&nbsp;编辑
                    </button>
                    <button title="" class="btn btn-sm btn-danger" id="btnDelete" type="button" data-original-title="删除投注" data-toggle="tooltip" data-widget="">
                        <i class="fa fa-times"></i>&nbsp;&nbsp;删除
                    </button>


                </label>
            </div><!-- /.col -->
        </h3>




        <div class="col-sm-3" style="border:solid 1px  #e4ddde;width:365px!important;">
            <div class="box box-primary">

                <div class="box-body">
                    <div id="treeDiv" class="portlet-body" style="min-height:729px;max-height:729px;overflow-y:auto">
                    </div>
                </div>
            </div>
        </div>


        <div  style="width:calc(100%-365px)!important;">
            <div class="table-scrollable" style="max-height:730px;overflow:auto;">
                <table class="table table-striped table-bordered table-hover dataTable no-footer" role="grid" aria-describedby="sample_2_info" id="odd-table">
                    <thead>
                        <tr role="row">
                            <th class="table-checkbox" style="width:40px;text-align:center;"><input class="group-checkable checkAll" id="checkAll1" type="checkbox"></th>
                            <th tabindex="0" aria-label="" class="text-center" style="width:30px!important;">
                                序
                            </th>
                            <th tabindex="0" aria-label="" class="text-center" style="width:85px!important;padding:2px 0px 2px 0px;">
                                发单时间
                            </th>

                            @*<th tabindex="0" aria-label="">
            预约截止时间
        </th>
        <th tabindex="0" aria-label="">
            跟单截止时间
        </th>*@
                            <th tabindex="0" aria-label="" class="text-center" style="width:40px!important;">
                                站
                            </th>
                            <th tabindex="0" aria-label="" class="text-center" style="width:85px!important;">
                                账号
                            </th>
                            <th tabindex="0" aria-label="" class="text-center" style="width:50px!important;">
                                金额
                            </th>
                            <th tabindex="0" aria-label="" class="text-center" style="width:50px!important;">
                                奖金
                            </th>
                            <th tabindex="0" aria-label="" class="text-center" style="width:45px!important;">
                                赔率
                            </th>
                            <th tabindex="0" aria-label="" class="text-center" style="width:60px!important;">
                                状态
                            </th>
                            <th tabindex="0" aria-label="" class="text-center" style="width:60px!important;">
                                倒计时
                            </th>
                            <th tabindex="0" aria-label="" class="text-center" style="width:45px!important;">
                                红包
                            </th>
                            <th tabindex="0" aria-label="" class="text-center" style="width:65px!important;">
                                跟单
                            </th>
                            <th tabindex="0" aria-label="" class="text-center" style="width:50px!important;">
                                人数
                            </th>


                            <th tabindex="0" aria-label="" style="min-width:350px!important;">
                                投注内容
                            </th>
                            <th tabindex="0" aria-label="" class="text-center" style="width:45px!important;">
                                说明
                            </th>

                            <th tabindex="0" aria-label="" class="text-center" style="width:45px!important;">
                                指令
                            </th>
                            <th tabindex="0" aria-label="" class="text-center" style="width:45px!important;">
                                下单
                            </th>
                            <th tabindex="0" aria-label="" class="text-center" style="width:45px!important;">
                               执行
                            </th>
                            <th tabindex="0" aria-label="" class="text-center" style="width:45px!important;">
                                编辑
                            </th>

                        </tr>
                    </thead>
                    <tbody id="tableBody"></tbody>
                </table>
            </div>

            <div class="col-sm-2 pagination" id="grid_paging_part" style="margin:5px 0 5px 0;"><div class="input-group"><span class="input-group-btn"><button class="btn btn-inverse btn-xs btn-white" id="first-btn" type="button"><span class="ace-icon icon-on-right "></span>首页</button></span><span class="input-group-btn"><button class="btn btn-inverse btn-xs btn-white" id="prev-btn" type="button"><span class="ace-icon icon-on-right "></span>上一页 </button></span><input class="input-sm  default" id="inputPage" style="width:60px;height:26px;" type="text" placeholder="页数"> <span class="input-group-btn"> <button class="btn btn-inverse btn-xs btn-white " id="jump-btn" type="button"><span class="ace-icon icon-on-right "></span> 跳转</button> </span><span class="input-group-btn"> <button class="btn btn-inverse btn-xs btn-white" id="next-btn" type="button"> <span class="ace-icon icon-on-right "></span>下一页</button></span><span class="input-group-btn"><button class="btn btn-inverse btn-xs btn-white" id="last-btn" type="button"><span class="ace-icon icon-on-right "></span>尾页 </button></span><span class="input-group-btn"><span class="label pager-msg">  共2条,当前1/1页</span> </span></div></div>

        </div>

    </div>
</div>

<div id="editBalanceModal" tabindex="-1" class="modal fade in" aria-hidden="true">
    <div class="modal-dialog">
        <div class="box box-info">
            <form class="form-horizontal">
                <input type="hidden" id="OddUserId1" />
                <div class="box-body">
                    <div class="form-group">
                        <label class="col-sm-2 control-label" for="Account">账号</label>
                        <div class="col-sm-10">
                            <input class="form-control" id="Account" type="text" placeholder="账号" readonly="readonly">
                        </div>
                    </div>


                    <div class="form-group">
                        <label class="col-sm-2 control-label" for="">账户余额</label>
                        <div class="col-sm-10">
                            <input id="AccountBalance" class="form-control" type="text">
                        </div>
                    </div>
                </div>
                <div class="box-footer">
                    <div class="pull-right box-tools">
                        <button id="btnBalanceSave" class="btn btn-sm btn-primary" type="button">保存</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>


<div id="downloadModal" tabindex="-1" class="modal fade in" aria-hidden="true">
    <form action="/Odd/DownloadFile" id="downloadForm" class="form-horizontal">
        <div class="modal-dialog">
            <div class="box box-info">
                <input  type="hidden" name="dSid" id="dSid"/>
                <div class="box-body">
                    <div class="form-group">
                        <label class="col-sm-2 control-label" for="">开始时间</label>
                        <div class="col-sm-10">
                            <input name="sTime" id="sTime" class="form-control datepicker" style="width:300px;" />
                        </div>
                    </div>

                </div>
                <div class="box-body">
                    <div class="form-group">
                        <label class="col-sm-2 control-label" for="">截止时间</label>
                        <div class="col-sm-10">
                            <input name="eTime" id="eTime" class="form-control datepicker" style="width:300px;" />
                        </div>
                    </div>

                </div>
                <div class="box-footer">
                    <div class="pull-right box-tools">
                        <button id="submitBtnDownload" class="btn btn-sm btn-primary" type="button">确定</button>
                    </div>
                </div>
            </div>
        </div>
    </form>


</div>

<div id="editRemarkModal" tabindex="-1" class="modal fade in" aria-hidden="true">
    <div class="modal-dialog">
        <div class="box box-info">
            <form class="form-horizontal">
                <input type="hidden" id="OddUserId" />
                <div class="box-body">
                    <div class="form-group">
                        <label class="col-sm-2 control-label" for="Account">账号</label>
                        <div class="col-sm-10">
                            <input class="form-control" id="EAccount" type="text" placeholder="账号" readonly="readonly">
                        </div>
                    </div>


                    <div class="form-group">
                        <label class="col-sm-2 control-label" for="">备注</label>
                        <div class="col-sm-10">
                            <input id="ERemark" class="form-control" type="text">
                        </div>
                    </div>
                </div>
                <div class="box-footer">
                    <div class="pull-right box-tools">
                        <button id="btnRemarkSave" class="btn btn-sm  btn-primary" type="button">保存</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

@Html.Partial("Edit")
@Html.Partial("Add")
@Html.Partial("EditOddContent")


<script src="~/assets/js/bootstrap-datetimepicker.js"></script>
<script src="~/assets/js/locales/bootstrap-datetimepicker.zh-CN.js"></script>


<script>
    //选中的投注单编号
    var selectedId = -1;
    //选中的操盘账号编号
    var selectedOddUerId = 0;

    //编辑内容窗口里面的行索引

    var selectedOddUser = {};


    var selectedOddId = 0;
    var rowIndex = 1;
    var allUsers = [];
    var allSites = [];
    var sh;
    var sh1;
    var triggerTime1;
    var allAppUser = [];
    var isTe = false;
    var pageIndex = 1;
    var pageSize = 20;

    var siteJson = {};


    $(function () {
        $(document).attr("title", "方案");
        $("#oddState").select2({
            minimumResultsForSearch: -1
        });

        $("input[name=oddMoneyType]").change(function () {

            LoadTables(1, 20);
        });

        $("#oddState").change(function () {

            LoadTables(1, 20);
        });


        $(document).delegate("#Descption", "input propertychange", function () {


            $("#textNumber").html($(this).val().length);

        });


        // 编辑备注
        $("#oddUserName").click(function () {

            if (selectedOddUerId <= 0) {
                alert("请选择账号");
                return;
            }
            $.ajax({
                type: "Get",
                url: "/OddUser/Get?id=" + selectedOddUerId + "&_t=" + new Date().getTime(),
                success: function (d) {
                    var data = d.data;
                    $("#OddUserId").val(data.id);
                    $("#EAccount").val(data.account);
                    $("#ERemark").val(data.remark);

                    var dialog = $("#editRemarkModal").removeClass('hide').dialog({
                        modal: true,
                        title: '编辑备注',
                        title_html: false,
                        width: 650,
                        height: 360

                    });

                    //$("#editRemarkModal").modal("show");
                }
            });
        })

        $("#submitBtnDownload").click(function () {
            var s1 = $("#sTime").val();
            var s2 = $("#eTime").val();

            if (selectedOddUerId > 0) {
                layer.alert("请选择用户前面的站点");
                return;
            }
            $("#dSid").val((selectedOddUerId*-1));
            var isTrue = true;
            if (s1.length == 0 || s2.length == 0) {
                layer.alert("开始时间或截止时间不能为空");
                isTrue = false;
            }

            if (new Date(s1) > new Date(s2)) {
                layer.alert("开始时间必须小于截止时间");
                isTrue = false;

            }
            if (isTrue) {
                $("#downloadForm").submit();
                $(".ui-dialog-titlebar-close").trigger("click");
            } else {

                return false;
            }
        });

        $("#specialCase").click(function () {
            isTe = true;
            $("#State").val("完成");
            $("#OwnBonus").removeAttr("readonly");
            $("#SiteId").attr("disabled", "disabled");
            $("#CreateOddUserId").attr("disabled", "disabled");
            $("#CreateTime").attr("readonly", "readonly");
            $("#DocumentaryUserCount").attr("readonly", "readonly");
            $("#DocumentaryMoney").attr("readonly", "readonly");
            $("#ProfitAndLoss").attr("readonly", "readonly");
            $("#Remark").attr("readonly", "readonly");
        });

        $(".datepicker").datetimepicker({
            language: "zh-CN",
            autoclose: true,//选中之后自动隐藏日期选择框
            todayBtn: true,//今日按钮
            format: "yyyy-mm-dd hh:ii"
        });


        $("#btnAdd").click(function () { Add(); });
        $("#btnEdit").click(function () { Edit(this); });
        $("#btnEditContent").click(function () { EditOddContent(this); });
        $("#btnSave").click(function () { Save(); });
        $("#btnDelete").click(function () { DeleteMulti(this); });
        //$(".checkAll").click(function () { CheckAll(this) });

        $(document).delegate(".checkAll", "click", function () { CheckAll(this);});
        $("#btnAddSave").click(AddSave);
        $("#btnAddData").click(function () {
            var isAllViable = true;
            $.each($(".odd-bet-row:gt(0)"), function (i, n) {
                if (!$(n).is(':visible')) {
                    isAllViable = false;
                    $(n).fadeIn();
                    return false;
                }
            });
            if (isAllViable) {
                layer.alert("最大只支持投注5注");
            }
        });

        // 编辑余额
        $("#ab").click(function () {
            if (selectedOddUerId <= 0) {
                alert("请选择账号");
                return;
            }
            $.ajax({
                type: "Get",
                url: "/OddUser/Get?id=" + selectedOddUerId + "&_t=" + new Date().getTime(),
                success: function (d) {
                    var data = d.data;
                    $("#OddUserId1").val(data.id);
                    $("#Account").val(data.account);
                    $("#AccountBalance").val(data.accountBalance);

                    var dialog = $("#editBalanceModal").removeClass('hide').dialog({
                        modal: true,
                        title: '编辑余额',
                        title_html: false,
                        width: 650,
                        height: 240

                    });
                    //$("#editBalanceModal").modal("show");
                }
            });
            return false;
        });


        $("#btnDownload").click(function () {

            var dialog = $("#downloadModal").removeClass('hide').dialog({
                modal: true,
                title: '导出',
                title_html: false,
                width: 650,
                height: 280

            });
            //$("#downloadModal").modal("show");
        });

        // 保存余额
        $("#btnBalanceSave").click(function () {
            var postData = {
                dto: {
                    Id: $("#OddUserId1").val(),
                    AccountBalance: $("#AccountBalance").val()
                }

            }
            $.ajax({
                type: "POST",
                data: postData,
                url: "/OddUser/EditBalance",
                success: function (d) {
                    if (d.success) {
                        GetAllUsers();
                        $("#ab span").html($("#AccountBalance").val());
                        //$("#editBalanceModal").modal("hide");
                        $(".ui-dialog-titlebar-close").trigger("click");
                    } else { 

                        layer.alert(d.message);
                    }
                }
            });

        });

        // 保存备注
        $("#btnRemarkSave").click(function () {

            var postData = {
                dto: {
                    Id: $("#OddUserId").val(),
                    Remark: $("#ERemark").val()
                }

            }
            $.ajax({
                type: "POST",
                data: postData,
                url: "/OddUser/EditRemark",
                success: function (d) {
                    if (d.success) {
                    GetAllUsers();
                    $("#remark").html($("#ERemark").val());
                    //$("#editRemarkModal").modal("hide");
                    $(".ui-dialog-titlebar-close").trigger("click");
                    } else {

                        layer.alert(d.message);
                    }
                }
            });
        });

        $(document).delegate(".confirm-status", "click", function () {
            var id = $(this).attr("oddId");
            if (confirm("确认已经下单?")) { 
                AjaxData("/Odd/UpdateCertification", "oddId=" + id, "Get", $(this), function (d) {
                    if (d.success) {
                        layer.alert("更新成功");
                        LoadTables(pageIndex, pageSize);

                    } else { 

                        layer.alert(d.message);
                    }

                })

            }
        });

        $(document).delegate("#sId", "change", function (e) {
            var id = $(this).val();
            var siteUsers = allUsers.Where(function (x) { return x.siteId == id });
            var ss = "<option value='-1'>请选择</option>";
            $.each(siteUsers, function (i, item) {
                ss += "<option value='" + item.id + "'>" + item.account + "</option>"
            });

            $("#uId").empty().html(ss);
            $("#uId").select2();
            //$("#InPlatformOddUserId").empty().html(ss);
            //$("#InPlatformOddUserId").select2();
        });

        $(document).delegate("#SiteId", "change", function (e) {
            var id = $(this).val();
            var siteUsers = allUsers.Where(function (x) { return x.siteId == id });
            var ss = "<option value='-1'>请选择</option>";
            $.each(siteUsers, function (i, item) {
                ss += "<option value='" + item.id + "'>" + item.account + "</option>"
            });

            $("#CreateOddUserId").empty().html(ss);
            $("#CreateOddUserId").select2();
            //$("#InPlatformOddUserId").empty().html(ss);
            //$("#InPlatformOddUserId").select2();
        });


        $(document).delegate(".editContent", "click", function () {
            $(".checkboxs").each(function () {
                $(this).removeAttr("checked");

            });
            var ck = $(this).parent().find("input:checkbox");
            //ck.prop('checked', !ck.prop('checked'));
            ck.prop('checked', "checked");
            $("#btnEditContent").trigger("click");
        });

        $(document).delegate(".edit", "click", function () {
            $(".checkboxs").each(function () {
                $(this).removeAttr("checked");

            });
            var ck = $(this).parent().find("input:checkbox");
            ck.prop('checked', "checked");

            $("#btnEdit").trigger("click");
        });

        $("#btnLoadRoot").click(function () {
            selectedId = 0;
            pageIndex = 1;
            LoadTables(pageIndex, 20);
        });


        //loadTables(1, 10);

        GetAllSites();
        GetAllUsers();
        GetAllAppUser();

        $("#cancleState").click(function () {
            if ($("#State").val() == "预约") {
                $("#State").val("撤销");
            } else {
                layer.alert("只有预约单才可以撤销");

            }
        });
        $("#checkState").click(function () {
            if ($("#State").val() == "待确认" || $("#State").val() == "完成") {
                $("#State").val("完成");
            } else {
                layer.alert("只有待确认的投注单才可以确认");
            }
        });
    });


    function getChildrenSite(siteArr, siteId) {
        siteArr[siteId]=0;
        var tempJson = siteJson[siteId];
        if (tempJson == null || tempJson.length < 1) return;
        for (var i = 0; i < tempJson.length; i++) {
            getChildrenSite(siteArr,tempJson[i]);
        }
    }


    function GetAllAppUser() {
        $.get("/AppUser/GetAllUser", "").done(function (d) {
            allAppUser = d.data;
            var ss = "<option value='-1' >请选择操盘手</option>";
            $.each(allAppUser, function (i, item) {
                ss += "<option value='" + item.id + "'>" + item.text + "</option>"
            });
            $("#aId,#AppUserId").empty().html(ss);
            $("#aId,#AppUserId").select2({
                multiple: false,
                minimumResultsForSearch: -1
            });
        });

    }



    function GetAllSites() {
        $.get("/Site/GetAllSites", "").done(function (d) {
            allSites = d.data;
            var ss = "<option value='-1' >请选择站点</option>";

            var s = "";

            $.each(allSites, function (i, item) {
                var tempJson = siteJson[item.parentId];
                if (tempJson == null || tempJson.length < 1) {
                    tempJson = [];
                    tempJson.push(item.id);
                    siteJson[item.parentId] = tempJson;
                } else { 
                    tempJson.push(item.id);
                    siteJson[item.parentId] = tempJson;
                }
             });

            $.each(allSites.GroupBy(function (x) { return x.type }), function (i, n) {

                s += "<option value='" + n.GroupValue + "'>" + n.GroupValue + "</option>";
            });

            $.each(allSites, function (i, item) {
                ss += "<option value='" + item.id + "'>" + item.name + "</option>"
            });

            //$("#dSid").select2("val", ["自身"]);

            $("#sId").empty().html(ss);
            $("#sId").select2({
                placeholder: '请选择',
                multiple: false

            });
            $("#SiteId").empty().html(ss);
            $("#SiteId").select2({
                placeholder: '请选择',
                multiple: false

            });
        });

    }
    function GetAllUsers() {
        $.get("/OddUser/GetAllUsers", "").done(function (d) {
            allUsers = d.data;
            var ss = "<option value='-1' >请选择账号</option>";
            $.each(allUsers, function (i, item) {
                ss += "<option value='" + item.id + "'>" + item.account + "</option>"
            });
            $("#uId").empty().html(ss);
            $("#uId").select2();
            $("#CreateOddUserId").empty().html(ss);
            $("#CreateOddUserId").select2();
            InitTree();
        });
    }


    //如果值为0 则不显示
    function RemoveNumberZero(value) {
        var result = "";
        if (parseInt(value * 100) != 0) {
            result = value;
        }
        return result;
    }


    //日期转换成周几
    function DayToWeekName(str) {
        var weekDay = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
        var myDate = new Date(Date.parse(str.replace(/-/g, "/")));
        return weekDay[myDate.getDay()];
    }

    function checkRate(value) {
        var re = /^-?\\d+$/; //判断字符串是否为数字 //判断正整数 /^[1-9]+[0-9]*]*$/

        if (!re.test(value)) {

            return false;
        }
        return true;
    }


    //加载功能树
    function InitTree() {
        $.jstree.destroy();
        $.ajax({
            type: "Get",
            url: "/OddUser/GetRedBlackData?_t=" + new Date().getTime(),    //获取数据的ajax请求地址
            success: function (d) {
                $('#treeDiv').jstree({       //创建JsTtree
                    'core': {
                        'data': d.data,        //绑定JsTree数据
                        "multiple": false    //是否多选
                    },
                    "plugins": ["state", "types", "wholerow"]  //配置信息
                });
                $("#treeDiv").on("ready.jstree", function (e, data) {   //树创建完成事件
                    data.instance.open_all();    //展开所有节点
                    if (selectedOddUerId == 0) {
                        data.instance.select_node(-1);
                    }

                });

                $("#treeDiv").on('changed.jstree', function (e, data) {   //选中节点改变事件
                    var node = data.instance.get_node(data.selected[0]);  //获取选中的节点
                    if (node) {
                        selectedOddUerId = node.id;

                        var n = Number(selectedOddUerId);

                        if (!isNaN(n)) {
                            if (selectedOddUerId > 0) {
                                $("#ab span").html(allUsers.FirstOrDefault(function (x) { return x.id == selectedOddUerId; }).accountBalance);
                                $("#remark").html(allUsers.FirstOrDefault(function (x) { return x.id == selectedOddUerId; }).remark);
                                $("#oddUserName").html(allUsers.FirstOrDefault(function (x) { return x.id == selectedOddUerId; }).account);
                            } else if (selectedOddUerId < 0) {

                                var arr = {};
                                getChildrenSite(arr, parseInt(selectedOddUerId)*-1);

                                $("#oddUserName").html("");
                                $("#remark").html("");
                                $("#ab span").html(allUsers.Where(function (x) {
                                    return arr[x.siteId] != null;
                                }).Sum(function (x) { return x.accountBalance; }).toFixed(0));
                            } else {
                                $("#oddUserName").html("");
                                $("#remark").html("");
                                $("#ab span").html(allUsers.Sum(function (x) { return x.accountBalance; }).toFixed(0));

                            }
                        } else {
                            $("#oddUserName").html("");
                            $("#remark").html("");
                            $("#ab span").html(allUsers.Sum(function (x) { return x.accountBalance; }).toFixed(0));
                        }
                        //GetOddUserById(selectedOddUerId);
                        pageIndex = 1;
                        LoadTables(pageIndex, pageSize);
                    };
                });
            }
        });
    }
    //全选
    function CheckAll(obj) {
        $(".checkboxs").each(function () {
            if (obj.checked == true) {
                $(this).prop("checked", true)
            }
            if (obj.checked == false) {
                $(this).prop("checked", false)
            }
        });
    };


    function CheckBeyondTheDeadline(odd) {
        var isTrue = true;
        var date1 = new Date();
        var date2 = new Date(odd.createTime);

        if (undefined != date2) {
            var s1 = date1.getTime(), s2 = date2.getTime();
            var total = (s1 - s2) / 1000;
            if (total > 0) {

                var day = parseInt(total / (24 * 60 * 60));
                var site = allSites.FirstOrDefault(function (x) { return x.id == odd.siteId });
                if ((parseInt(site.remark) == 1 && day >= 15) || (parseInt(site.remark) == 2 && day >= 7) || (parseInt(site.remark) == 3 && day >= 30)) {
                    isTrue = false;
                }
            }
        }
        return isTrue;
    }


    //加载投注单列表数据
    function LoadTables(startPage, pageSize) {
        $("#tableBody").html("");
        $("#checkAll").prop("checked", false);


        var oddMoneyTypes = [];
        $.each($("input[name=oddMoneyType]:checked"), function () {
            oddMoneyTypes.push($(this).val());
        });


        datas = {
            oddUserId: selectedOddUerId,
            oddMoneyTypes: oddMoneyTypes,
            oddState: $("#oddState").val(),
            startPage: startPage,
            pageSize: pageSize
        }
        $.ajax({
            type: "POST",
            url: "/Odd/GetNewOddByOddUserId",
            data: datas,
            success: function (d) {
                var data = d.data;
                $.each(data.result, function (i, item) {

                    var isTrue = CheckBeyondTheDeadline(item);
                    var c = (isTrue ? "" : "text-grays");
                    var tr = "<tr>";
                    tr += "<td align='center'><input type='checkbox' class='checkboxs' value='" + item.id + "'/></td>";
                    tr += "<td class='center " + c + "'>" + (pageSize * (startPage - 1) + (i + 1)) + "</td>";
                    tr += "<td class='text-center " + c + "'>" + new Date(item.createTime).format("M-dd hh:mm") + "</td>";

                    //tr += "<td>" + item.bespeakCutoffTime+ "</td>";
                    //tr += "<td>" + item.documentaryCutoffTime + "</td>";

                    var user = allUsers.FirstOrDefault(function (x) { return x.id == item.createOddUserId });
                    // 站点名
                    tr += "<td class='center " + c + "'>" + allSites.FirstOrDefault(function (x) { return x.id == user.siteId }).name + "</td>";
                    tr += "<td class='center " + c + "'>" + user.account + "</td>";

                    var k = "";
                    if (item.ownBonus > 0) {
                        k = "red";
                    }

                    tr += "<td class='text-right  " + k + "'>" + RemoveNumberZero(item.ownPurchaseMoney) + "</td>";
                    tr += "<td class='text-right  " + k + "'>" + RemoveNumberZero(parseInt(item.ownBonus)) + "</td>";
                    tr += "<td class='text-right " + c + "'>" + RemoveNumberZero(item.ownPurchaseMoney == 0 ? 0 : (item.ownBonus / item.ownPurchaseMoney).toFixed(2)) + "</td>";
                    //tr += "<td>" + item.ownPurchaseRebate + "</td>";
                    //tr += "<td>" + item.documentaryRebate + "</td>";

                    tr += "<td class='text-center " + c + "'>" + StateData.SingleOrDefault(function (x) { return x.id == item.state }).text + "</td>";
                    tr += "<td class='text-center " + c + "'>" + ShowTime(item) + "</td>";
                    tr += "<td class='text-right " + c + "'>" + RemoveNumberZero(item.profitAndLoss) + "</td>";

                    tr += "<td class='text-right " + c + "'>" + RemoveNumberZero(item.documentaryMoney) + "</td>";
                    tr += "<td class='text-right " + c + "'>" + RemoveNumberZero(item.documentaryUserCount) + "</td>";



                    tr += "<td class='editContent cursor' data-id='" + item.id + "' style='width:310px;'>" + GetContentString(item) + "</td>";
                    tr += "<td ><a href='#' title='" + item.descption + "'>" + (item.descption == null ? "" : item.descption.substring(0, 2)) + "</a></td>";

                    tr += "<td class='edit cursor' data-id='" + item.id + "'>" + item.appUserName + "</td>";
                    tr += '<td><button class="btn btn-minier btn-primary confirm-status" oddId="' + item.id + '"  ' + (item.certification ? 'disabled="true"' : '') + '>' + (item.certification ? '已下' : '下单') + '</button></td>';
                    tr += "<td>" + ((item.confirmAppUserName == item.appUserName || item.confirmAppUserName==null ) ? "" : item.confirmAppUserName) + "</td>";
                    tr += "<td>" + (item.lastEditAppUserName === item.appUserName ? "" : item.lastEditAppUserName) + "</td>";

                    tr += "</tr>";
                    $("#tableBody").append(tr);
                });
                $("#odd-table").chromatable({
                    width: "100%",
                    height: "730px",
                    scrolling: "yes"
                });


                $("#grid_paging_part").lagerPaper({
                    currentIndex: data.pageIndex,
                    pageSize: pageSize,
                    totalCount: data.totalCount,
                    pageCount: data.pageCount,
                    onPageChanged: function (e, pageIndex) {
                        LoadTables(pageIndex, pageSize);
                    }
                });


            }
        })
    };

    function ShowTime(data) {
        var ss = "";
        var date1 = new Date();
        var date2;
        if (data.state == 1) {
            date2 = new Date(data.bespeakCutoffTime);

        } else if (data.state == 2 || data.state == 3) {
            date2 = new Date(data.documentaryCutoffTime);

        } else {
            date2 = new Date(data.lotteryTime);
        }

        if (undefined != date2) {
            var s1 = date1.getTime(), s2 = date2.getTime();
            var total = (s2 - s1) / 1000;
            if (total < 0) {
                ss = "";

            } else {
                var day = parseInt(total / (24 * 60 * 60));
                var afterDay = total - day * 24 * 60 * 60;
                var hour = parseInt(afterDay / (60 * 60));
                var afterHour = total - day * 24 * 60 * 60 - hour * 60 * 60;
                var min = parseInt(afterHour / 60);
                ss = day + "    " + hour + ":" + min;
            }
        }
        return ss;
    }

    function GetContentString(data) {
        var ss = "";

        if (null != data.betDetailOddList && data.betDetailOddList.Count() > 0) {
            $.each(data.betDetailOddList, function (i, n) {

                var s = "";
                var pay = 1; var r = "";
                if (null != n.betDetailOddContentsList && n.betDetailOddContentsList.Count() > 0) {

                    $.each(n.betDetailOddContentsList, function (j, k) {
                        r += k.lotteryResults + "";
                        pay = pay * k.selectedOdds;
                        if (k.fixOdds == "" || parseInt(k.fixOdds) == 0) {
                            s += k.weekName + MatchResult.FirstOrDefault(function (x) { return x.id == k.selectedResult }).text;

                        } else {
                            s += k.weekName + "让" + k.fixOdds + MatchResult.FirstOrDefault(function (x) { return x.id == k.selectedResult }).text.replace("让", "");

                        }
                        if (k.lotteryResults == "1") {

                            s += "<span class='red'>" + k.selectedOdds + "</span>";
                        } else if (k.lotteryResults == "0") {
                            s += "<span class='blue'>" + k.selectedOdds + "</span>";
                        } else {
                            s += k.selectedOdds;

                        }
                        if (j < n.betDetailOddContentsList.Count() - 1) {
                            s += '|';
                        }
                    });
                }

                if (r == '1' || r == "11" || r == "1-1" || r == "11-1" || r == "111") {
                    ss += n.betCount + "倍<span class='red'>" + pay.toFixed(2) + " </span>" + s;

                } else if (r == "0" || r == '00' || r == '10' || r == '01' || r == '0-1' || r == '11'
                    || r == '110' || r == '101' || r == '100' || r == '011' || r == '001' || r == '010' || r == '011'
                    || r == '01-1' || r == '00-1' || r == '10-1' || r == '0-1-1'
                ) {
                    ss += n.betCount + "倍<span class='blue'>" + pay.toFixed(2) + " </span>&nbsp;" + s;

                } else {
                    ss += n.betCount + "倍" + pay.toFixed(2) + "&nbsp; " + s;

                }


                if (i < data.betDetailOddList.Count() - 1) {
                    ss += "<br/>";
                }

            });

        }
        return ss;
    }

    //新增
    function Add() {

        $("#cTime").val("");
        //$("#uId").select2("val", [-1]);
        $("#aRemark").val("");
        if (undefined != currenrUser && null != currenrUser) {
            $("#aId").select2("val", [currenrUser.id]);

        }
        // $("#Title").text("新增");

        var dialog = $("#addModal").removeClass('hide').dialog({
            modal: true,
            title: '新增',
            title_html: false,
            width: 650,
            height: 470

        });

        //弹出新增窗体
        //$("#addModal").modal("show");
    };

    //编辑
    function Edit(selector) {
        var ids = [];
        isTe = false;
        $(".checkboxs").each(function () {
            if ($(this).prop("checked") == true) {
                ids.push($(this).val());
            }
        });
        if (ids.length == 0) {
            layer.tips("请选择要编辑的记录", selector);
            return;
        };
        if (ids.length > 1) {
            layer.tips("不能同时编辑多条记录", selector);
            return;
        }

        selectedOddId = ids[0];

        $(".checkboxs").prop("checked", false);
        $.ajax({
            type: "Get",
            url: "/Odd/Get?id=" + ids[0] + "&_t=" + new Date().getTime(),
            success: function (d) {
                var data = d.data;
                var ids = [];
                ids.push(data.createOddUserId);
                $("#OwnBonus").attr("readonly", "readonly");
                $("#SiteId").removeAttr("disabled");
                $("#CreateOddUserId").removeAttr("disabled");

                $("#CreateTime").removeAttr("readonly");
                $("#DocumentaryUserCount").removeAttr("readonly");
                $("#DocumentaryMoney").removeAttr("readonly");
                $("#ProfitAndLoss").removeAttr("readonly");
                $("#Remark").removeAttr("readonly");



                $("#SiteId").val( [allUsers.FirstOrDefault(function (x) {
                    return x.id == data.createOddUserId;
                }).siteId]).trigger("change");

                $("#CreateOddUserId").val(ids).trigger("change");
                $("#AppUserId").val([data.appUserId]).trigger("change");
                $("#EditId").val(data.id);
                $("#CreateTime").val(data.createTime);
                $("#BespeakCutoffTime").val(data.bespeakCutoffTime);
                $("#DocumentaryCutoffTime").val(data.documentaryCutoffTime);
               
                $("#OwnPurchaseMoney").val(data.ownPurchaseMoney);
                $("#DocumentaryUserCount").val(data.documentaryUserCount);
                $("#DocumentaryMoney").val(data.documentaryMoney);
                $("#ProfitAndLoss").val(data.profitAndLoss);
                $("#OwnBonus").val(data.ownBonus);

                $("#BetWay").val(data.betWay);
                $("#Remark").val(data.remark);
                $("#Descption").val(data.descption);
                $("#Title").val(data.title);
                $("#textNumber").html($("#Descption").val().length);

                $("#State").val(StateData.FirstOrDefault(function (x) { return x.id == data.state }).text);


                var dialog = $("#editModal").removeClass('hide').dialog({
                    modal: true,
                    title: '编辑',
                    title_html: false,
                    width: 850,
                    height: 600

                });
                //$("#Title").text("编辑")
                //$("#editModal").modal("show");



                if (data.state == 1) {
                    triggerTime1 = data.bespeakCutoffTime;


                } else if (data.state == 3 || data.state == 2) {
                    triggerTime1 = data.documentaryCutoffTime;

                } else {
                    triggerTime1 = data.lotteryTime;
                }

                WriteSecondTime1();

            }
        })
    };

    function WriteSecondTime1() {
        var ss = "";
        var date1 = new Date();
        var date2 = new Date(triggerTime1);

        var s1 = date1.getTime(), s2 = date2.getTime();
        var total = (s2 - s1) / 1000;
        if (total < 0) {
            ss = "";

        } else {
            var day = parseInt(total / (24 * 60 * 60));
            var afterDay = total - day * 24 * 60 * 60;
            var hour = parseInt(afterDay / (60 * 60));
            var afterHour = total - day * 24 * 60 * 60 - hour * 60 * 60;
            var min = parseInt(afterHour / 60);
            var afterMin = total - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60;
            ss = day + "   " + hour + ":" + min;
        }
        $("#secondTime").val(ss);
    }

    //function DeleteCurrentRow(d) {
    //    var s = $(d).parent("div").parent("div").parent("div");
    //    $(s).find(".Id").val("");
    //    $(s).find(".BetCount").val("");
    //    $(s).find("select.match").select2("val", "");
    //    $(s).find(".odd").select2("val", "");
    //    s.hide();
    //}


    //function CreateSingleDetailOddRow()
    //{
    //    var ss = '<div class="box-body odd-bet-row"><div class="form-group col-md-3 col-sm-3"><label class="col-sm-4 control-label" for="inputPassword3">注数</label>';
    //    ss += ' <div class="col-sm-8"><input class="form-control BetCount" type="text" placeholder="注数" value="" /> </div> </div>';
    //    ss += ' <div class="form-group col-md-5 col-sm-5"><label class="col-sm-3 control-label" for="">比赛</label><div class="col-sm-9"><select class="form-control match" style="padding:0px;width:300px;" multiple="multiple"></select></div></div>';
    //    ss += ' <div class="form-group col-md-4 col-sm-4"><label class="col-sm-3 control-label" for="">内容</label><div class="col-sm-9"><select class="form-control odd" style="padding:0px;width:200px;" multiple="multiple"></select></div></div>';
    //    ss += '<div class="form-group col-md-1 col-sm-1"> <div class="col-sm-10"><button class="btn btn- info btn- xs"   onclick="DeleteCurrentRow(this)"><i class="fa fa- edit"></i> 删除 </button> </div> </div></div>';
    //    return ss;
    //}

    function AddSave() {

        if (parseInt($("#aId").val()) < 0 || parseInt($("#uId").val()) < 0) {
            layer.tips("请选中账号或操盘手", "#btnAddSave");
            return;
        }

        var postData = {
            "odd": {
                "CreateTime": $("#cTime").val(),
                "CreateOddUserId": $("#uId").val(),
                "Remark": $("#aRemark").val(),
                "OwnPurchaseMoney": $("#opMoney").val(),
                "SiteId": allUsers.FirstOrDefault(function (x) { return x.id == $("#uId").val(); }).siteId,
                "AppuserId": $("#aId").val()
            }
        };
        selectedOddUerId = $("#uId").val();
        $.ajax({
            type: "Post",
            url: "/Odd/Add",
            data: postData,
            success: function (data) {
                if (data.success) {
                    $("#addModal").modal("hide");
                    $.ajaxSetup({ cache: false });//缓存区清理
                    $("#treeDiv").jstree().deselect_all();
                    $('#treeDiv').jstree().select_node(selectedOddUerId);

                    $(".ui-dialog-titlebar-close").trigger("click");
                    //LoadTables(1, pageSize)

                    //$(node).trigger("click");
                } else {
                    layer.tips(data.message, "#btnAddSave");
                };
            }
        });

    }

    //保存
    function Save() {
        var postData = {
            "odd": {
                "Id": $("#EditId").val(),
                "CreateTime": $("#CreateTime").val(),
                "BespeakCutoffTime": $("#BespeakCutoffTime").val(),
                "DocumentaryCutoffTime": $("#DocumentaryCutoffTime").val(),
                "CreateOddUserId": $("#CreateOddUserId").val(),
                "SiteId": allUsers.FirstOrDefault(function (x) { return x.id == $("#CreateOddUserId").val(); }).siteId,
                "OwnPurchaseMoney": $("#OwnPurchaseMoney").val(),
                "DocumentaryUserCount": $("#DocumentaryUserCount").val(),
                "DocumentaryMoney": $("#DocumentaryMoney").val(),
                "OwnBonus": $("#OwnBonus").val(),
                "LotteryTime": $("#LotteryTime").val(),
                "BetWay": $("#BetWay").val(),
                "Remark": $("#Remark").val(),
                "AppUserId": $("#AppUserId").val(),
                "State": StateData.FirstOrDefault(function (x) { return x.text == $("#State").val() }).id,
                "ProfitAndLoss": $("#ProfitAndLoss").val(),
                "Descption": $("#Descption").val(),
                "Title":$("#Title").val()
            },
            "isTe": isTe
        };
        $.ajax({
            type: "Post",
            url: "/Odd/Edit",
            data: postData,
            success: function (data) {
                if (data.success) {

                    $(".ui-dialog-titlebar-close").trigger("click");
                    LoadTables(pageIndex, 20);
                } else {
                    layer.tips(data.message, "#btnSave");
                };
            }
        });
    };

    //批量删除
    function DeleteMulti(selector) {
        var ids = "";
        $(".checkboxs").each(function () {
            if ($(this).prop("checked") == true) {
                ids += $(this).val() + ","
            }
        });
        ids = ids.substring(0, ids.length - 1);
        if (ids.length == 0) {

            layer.tips("请选择要删除的记录", selector);
            return;
        };
        //询问框
        layer.confirm("您确认删除选定的记录吗？", {
            btn: ["确定", "取消"]
        }, function () {
            var sendData = { "ids": ids };
            $.ajax({
                type: "Post",
                url: "/Odd/DeleteMuti",
                data: sendData,
                success: function (data) {
                    if (data.success) {
                        LoadTables(pageIndex, 20);
                        layer.closeAll();
                    }
                    else {
                        layer.alert("删除失败！");
                    }
                }
            });
        });
    };
    //删除单条数据
    function DeleteSingle(id) {
        layer.confirm("您确认删除选定的记录吗？", {
            btn: ["确定", "取消"]
        }, function () {
            $.ajax({
                type: "POST",
                url: "/Odd/Delete",
                data: { "id": id },
                success: function (data) {
                    if (data.success) {
                        LoadTables(pageIndex, 20);
                        layer.closeAll();
                    }
                    else {
                        layer.alert("删除失败！");
                    }
                }
            })
        });
    };






    //创建比赛选项下拉框的内容
    function CreateMatchReultOption(selector, data) {
        $(selector).empty();
        var values = [];
        $.each(data, function (i, item) {
            var tr = '';
            $.each(item.jcHadOddsList, function (j, k) {
                //if (k.fixedOdds == '') {
                //    tr += "<option value='{\"WeekName\":\"" + item.matchNumber + "\",\"SelectedMatchId\":" + item.matchId + ",\"SelectedResult\":1,\"SelectedOdds\":" + k.homeOdds + ",\"FixOdds\":\"" + k.fixedOdds + "\"}'>" + item.matchNumber + "-胜-" + k.homeOdds + "</option>";
                //    tr += "<option value='{\"WeekName\":\"" + item.matchNumber + "\",\"SelectedMatchId\":" + item.matchId + ",\"SelectedResult\":2,\"SelectedOdds\":" + k.drawOdds + ",\"FixOdds\":\"" + k.fixedOdds + "}'>" + item.matchNumber + "-平-" + k.drawOdds + "</option>";
                //    tr += "<option value='{\"WeekName\":\"" + item.matchNumber + "\",\"SelectedMatchId\":" + item.matchId + ",\"SelectedResult\":3,\"SelectedOdds\":" + k.awayOdds + ",\"FixOdds\":\"" + k.fixedOdds + "}'>" + item.matchNumber + "-负-" + k.awayOdds + "</option>";
                //} else {
                //    tr += "<option value='{\"WeekName\":\"" + item.matchNumber + "\",\"SelectedMatchId\":" + item.matchId + ",\"SelectedResult\":4,\"SelectedOdds\":" + k.homeOdds + ",\"FixOdds\":\"" + k.fixedOdds + "\"}'>" + item.matchNumber + "-让球胜[" + k.fixedOdds + "]-" + k.homeOdds + "</option>";
                //    tr += "<option value='{\"WeekName\":\"" + item.matchNumber + "\",\"SelectedMatchId\":" + item.matchId + ",\"SelectedResult\":5,\"SelectedOdds\":" + k.drawOdds + ",\"FixOdds\":\"" + k.fixedOdds + "\"}'>" + item.matchNumber + "-让球平[" + k.fixedOdds + "]-" + k.drawOdds + "</option>";
                //    tr += "<option value='{\"WeekName\":\"" + item.matchNumber + "\",\"SelectedMatchId\":" + item.matchId + ",\"SelectedResult\":6,\"SelectedOdds\":" + k.awayOdds + ",\"FixOdds\":\"" + k.fixedOdds + "\"}'>" + item.matchNumber + "-让球负[" + k.fixedOdds + "]-" + k.awayOdds + "</option>";
                //}
                if (k.fixedOdds == '') {

                    var value1 = item.matchNumber + '|' + item.matchId + '|1|' + k.homeOdds + '|0';
                    var value2 = item.matchNumber + '|' + item.matchId + '|2|' + k.drawOdds + '|0';
                    var value3 = item.matchNumber + '|' + item.matchId + '|3|' + k.awayOdds + '|0';


                    if (!values.contains(value1)) {
                        tr += "<option value='" + value1 + "'>" + item.matchNumber + "胜" + k.homeOdds + "</option>";
                    }
                    if (!values.contains(value2)) {
                        tr += "<option value='" + value2 + "'>" + item.matchNumber + "平" + k.drawOdds + "</option>";
                    }
                    if (!values.contains(value3)) {
                        tr += "<option value='" + value3 + "'>" + item.matchNumber + "负" + k.awayOdds + "</option>";
                    }

                    values.push(value1);
                    values.push(value2);
                    values.push(value3);
                } else {
                    var value1 = item.matchNumber + '|' + item.matchId + '|4|' + k.homeOdds + '|' + k.fixedOdds;
                    var value2 = item.matchNumber + '|' + item.matchId + '|5|' + k.drawOdds + '|' + k.fixedOdds;
                    var value3 = item.matchNumber + '|' + item.matchId + '|6|' + k.awayOdds + '|' + k.fixedOdds;
                    if (!values.contains(value1)) {
                        tr += "<option value='" + value1 + "'>" + item.matchNumber + "让" + k.fixedOdds + "胜" + k.homeOdds + "</option>";
                    }
                    if (!values.contains(value2)) {
                        tr += "<option value='" + value2 + "'>" + item.matchNumber + "让" + k.fixedOdds + "平" + k.drawOdds + "</option>";
                    } if (!values.contains(value3)) {
                        tr += "<option value='" + value3 + "'>" + item.matchNumber + "让" + k.fixedOdds + "负" + k.awayOdds + "</option>";
                    }
                    values.push(value1);
                    values.push(value2);
                    values.push(value3);
                }
            });
            $(selector).append(tr);
        });
        $(selector).select2({
            placeholder: '请选择',
            multiple: true,
            minimumResultsForSearch: 4,
            maximumSelectionLength: data.length,
            allowClear: true
        });

    }


</script>


